import { defineStore } from 'pinia'
import http from '@/tools/http'
import cipher from '@/tools/cipher'

type User = {
    token: string
    account: string
    userName: string
    userMessageCount: number
    roleList: string[]
    authList: string[]
    currentPageName: string
    currentPageQuery: Object
    userDetails: UserInfo
}

export type UserInfo = {
    userId: string
    orgCode?: string
    accountStatus?: string
    userName: string
    idType?: string
    idCode?: string
    idBeginDate?: string
    idExpDate?: undefined
    birthday?: string
    sex?: string
    nationality?: string
    telephone?: string
    email?: string
    address?: string
    userAvatar: string
    remark?: string
}
export const useUserStore = defineStore('user', {
    state: (): User => ({
        token: "",
        account: "",
        userName: "",
        userMessageCount: 0,
        currentPageName: "",
        currentPageQuery: {},
        roleList: [],
        authList: [],
        userDetails: {
            userId: "",
            userName: "",
            userAvatar: ""
        }
    }),
    getters: {},
    actions: {
        hasAuth(auth: string) {
            return this.authList.includes(auth)
        },
        hasRole(role: string) {
            return this.roleList.includes(role)
        },
        refreshToken(token: string) {
            this.token = token
            sessionStorage.setItem("token", token)
        },
        loadToken() {
            if (this.token !== null && this.token !== "") {
                return
            }
            const token = sessionStorage.getItem("token")
            if (token) {
                this.token = token
            } else {
                this.token = ""
            }
        },
        loadAccountInfo(accountInfo?: User) {
            if (accountInfo) {
                if (accountInfo.account) {
                    this.account = accountInfo.account
                }
                if (accountInfo.userName) {
                    this.userName = accountInfo.userName
                }
                if (accountInfo.roleList) {
                    this.roleList = accountInfo.roleList
                }
                if (accountInfo.authList) {
                    this.authList = accountInfo.authList
                }
                sessionStorage.setItem("userInfo", cipher.sm4Encrypt(JSON.stringify({
                    account: this.account,
                    userName: this.userName,
                    roleList: this.roleList,
                    authList: this.authList
                })))
                this.countUserMessage()
            } else {
                if (this.token !== null && this.token !== "") {
                    return
                }
                const localUserInfoStr = sessionStorage.getItem("userInfo")
                if (localUserInfoStr !== null && localUserInfoStr !== "") {
                    const localUserInfo = JSON.parse(cipher.sm4Decrypt(localUserInfoStr))
                    this.account = localUserInfo.account
                    this.userName = localUserInfo.userName
                    this.roleList = localUserInfo.roleList
                    this.authList = localUserInfo.authList
                    this.countUserMessage()
                }

                const userAvatar = sessionStorage.getItem("userAvatar")
                if (userAvatar !== null && userAvatar !== "") {
                    this.userDetails.userAvatar = userAvatar
                } else {
                    this.userDetails.userAvatar = ""
                }
                this.loadToken()
            }
            this.loadCurrentPageName()
        },
        loadUserInfo() {
            const request = {
                userId: this.account
            }
            http.post("/user", request).then(({ data }) => {
                if (data.code === "0") {
                    this.userDetails.userId = data.data.userId
                    this.userDetails.orgCode = data.data.orgCode
                    this.userDetails.accountStatus = data.data.accountStatus
                    this.userDetails.userName = data.data.userName
                    this.userDetails.idType = data.data.idType
                    this.userDetails.idCode = data.data.idCode
                    this.userDetails.idBeginDate = data.data.idBeginDate
                    this.userDetails.idExpDate = data.data.idExpDate
                    this.userDetails.birthday = data.data.birthday
                    this.userDetails.sex = data.data.sex
                    this.userDetails.nationality = data.data.nationality
                    this.userDetails.telephone = data.data.telephone
                    this.userDetails.email = data.data.email
                    this.userDetails.address = data.data.address
                    this.userDetails.remark = data.data.remark
                    if (data.data.userAvatar && data.data.userAvatar !== "") {
                        this.userDetails.userAvatar = data.data.userAvatar
                        sessionStorage.setItem("userAvatar", this.userDetails.userAvatar)
                    } else {
                        this.userDetails.userAvatar = ""
                        sessionStorage.setItem("userAvatar", this.userDetails.userAvatar)
                    }
                }
            })
        },
        setUserAvatar(userAvatar: string) {
            this.userDetails.userAvatar = userAvatar
            sessionStorage.setItem("userAvatar", userAvatar)
        },
        countUserMessage() {
            const request = {
                userId: this.account,
                messageStatus: "0"
            }
            http.post("/user/message/count", request).then(({ data }) => {
                if (data.code === "0") {
                    this.userMessageCount = data.data
                }
            })
        },
        clear() {
            this.account = ""
            this.userName = ""
            this.userDetails = {
                userId: "",
                userName: "",
                userAvatar: "",
            }
            this.roleList.length = 0
            this.authList.length = 0
            this.token = ""
            sessionStorage.clear()
        },
        loadCurrentPageName() {
            const pageName = sessionStorage.getItem("currentPageName")
            if (pageName) {
                this.currentPageName = pageName
            } else {
                this.currentPageName = ""
            }
            const pageQueryStr = sessionStorage.getItem("currentPageQuery")
            if (pageQueryStr) {
                this.currentPageQuery = JSON.parse(pageQueryStr)
            } else {
                this.currentPageQuery = {}
            }
        },
        setCurrentPageName(pageName: string) {
            this.currentPageName = pageName
            sessionStorage.setItem("currentPageName", pageName)
        },
        setCurrentPageQuery(query: Object) {
            this.currentPageQuery = query
            sessionStorage.setItem("currentPageQuery", JSON.stringify(query))
        },
        getCurrentPageQuery() {
            if (this.currentPageQuery && this.currentPageQuery !== null) {
                return this.currentPageQuery
            }
            const pageQueryStr = sessionStorage.getItem("currentPageQuery")
            if (pageQueryStr) {
                this.currentPageQuery = JSON.parse(pageQueryStr)
            } else {
                this.currentPageQuery = {}
            }
            return this.currentPageQuery
        }
    }
})